 //
//  WBStatusPictureView.swift
//  CZweibo
//
//  Created by jyh on 2017/12/12.
//  Copyright © 2017年 jyh. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    
    var urls: [WBStatusPicture]? {
        didSet {
            // 隐藏所有 imageView
            for v in subviews {
                v.isHidden = true
            }
            
            // 设置图像
            var index = 0
            for url in urls ?? [] {
                // 获取对于索引的 imageView
                let iv  = subviews[index] as! UIImageView
                
                // 处理4张图像
                if index == 1 && urls?.count == 4 {
                    index += 1
                }
                
                // 设置图像
                iv.hg_setImage(urlStr: url.thumbnail_pic, placeholderImage: nil)
                // 显示 imageView
                iv.isHidden = false
                
                index += 1
            }
        }
    }

    @IBOutlet weak var heightCons: NSLayoutConstraint!
    
    override func awakeFromNib() {
        setupUI()
    }
}

extension WBStatusPictureView {
    
    // 超出边界的内容不显示

    //1. cell 中所有的控件都是要提前准备好
    //2. 设置的时候,根据数据决定是否显示
    //3. 不要动态创建控件.否则很消耗性能
    
    fileprivate func setupUI() {
        
        // 设置背景颜色,根据父视图的背景颜色设置
        backgroundColor = superview?.backgroundColor
        
        clipsToBounds = true
        let count = 3
        let rect = CGRect(x: 0, y: WBStatusPictureViewOutterMargin,
                          width: WBStatusPictureItemWidth,
                          height: WBStatusPictureItemWidth)
        // 循环创建 9 个 imageView
        for i in 0..<count * count{
            
            let iv = UIImageView()
            
            // 行 -> Y
            let row = CGFloat(i / count)
            // 列 -> X
            let col = CGFloat(i % count)
            let xOffSet = col * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            let yOffset = row * (WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
            iv.frame = rect.offsetBy(dx: xOffSet, dy: yOffset)
            
            addSubview(iv)
        }
        
    }
}
